<template>
	<view class="tabContent" v-show="true">
		<view class="param-title">基本信息</view>
		<view class="param-item">
			<label>姓名</label>
			<text class="text">{{ userInfo.nickName }}</text>
		</view>
		<view class="param-item">
			<label>年级</label>
			<button @click="openGradeTermPopup" class="button" plain="true">{{ userInfo.stage }} {{ userInfo.grade }}
				({{ userInfo.term }})</button>
		</view>
		<vk-data-goods-sku-popup ref="skuPopup" v-model="gradeTermPopupData.show" border-radius="20" :z-index="990"
			:localdata="gradeGoodsInfo" :selected-init="true" :mode="gradeTermPopupData.mode"
			:theme="gradeTermPopupData.theme" :show-close="gradeTermPopupData.showClose"
			:hide-stock="gradeTermPopupData.hideStock" :mask-close-able="gradeTermPopupData.maskCloseAble"
			@open="onOpenGradeTermPopup" @close="onCloseGradeTermPopup"
			@add-cart="confirmGradeTermSelection"></vk-data-goods-sku-popup>
		<!-- 考试信息表格 -->
		<view class="title-box">
			<view class="title-item">考试年级</view>
			<view class="title-item">考试名称</view>
			<view class="title-item">考试日期</view>
		</view>
		<view v-for="(examInfo, examInfoIndex) in userInfo.examInfo" :key="examInfoIndex">
			<uni-card>
				<uni-collapse accordion :value="activeCollapseItems[examInfoIndex]"
					@change="handleCollapseChange($event, examInfoIndex)">
					<uni-collapse-item v-for="(exam, examIndex) in examInfo.examList" :key="examIndex"
						:name="examIndex.toString()">
						<template v-slot:title>
							<view class="collapse-title-box">
								<view class="collapse-title">{{ examInfo.grade }}<span
										class="term-font">{{examInfo.term[0]}}</span></view>
								<view class="collapse-title">{{ exam.examName }}</view>
								<view class="collapse-title">{{ exam.examDate }}</view>
							</view>
						</template>
						<!-- 考试信息表格中的两个按钮 -->
						<view class="mini-button-box">
							<button type="primary" size="mini"
								@click="editExamInfo(examInfoIndex, examIndex)">前往编辑</button>
							<button type="warn" size="mini" @click="delExamInfo(examInfoIndex, examIndex)">删除</button>
						</view>
						<!-- 考试信息表格中的展示科目成绩 -->
						<uni-card>
							<!-- <uni-grid :column="3" :show-border="false">
								<uni-grid-item v-for="(subject, subjectIndex) in exam.scoreList" :key="subjectIndex"
									style="height:100rpx">
									<view class="subject-text-box">
										<view class="text-name">
											<uni-tag :text='subject.name' :type="subject.tagType"
												@click="selectSubject(subject, examInfoIndex, examIndex)"
												size="big"></uni-tag>
										</view>
										<view class="text-score">{{ subject.score }}</view>
									</view>
								</uni-grid-item>
							</uni-grid> -->


							<checkbox-group class="checkbox-group" @change="handleCheckboxChange">
								<view class="checkbox" v-for="(subject, subjectIndex) in exam.scoreList"
									:key="subjectIndex">
									<view>
										<checkbox value="subject.score" checked="true" />
									</view>
									<view>
										<view class="subject-name">
											{{subject.name}}
										</view>
										<view class="subject-score">
											{{subject.score}}
										</view>
									</view>
								</view>
							</checkbox-group>



						</uni-card>
						<uni-card>
							<uni-list :border="false">
								<uni-list-item title="考试总分" note="点击科目(多个)自动计算"
									:rightText="totalScore[examInfoIndex][examIndex].toString() + ' / 满分：' + totalFull[examInfoIndex][examIndex].toString() " />
								<uni-list-item title="平均分" note="点击科目(可选)自动计算"
									:rightText="averageScore[examInfoIndex][examIndex] + ''" />
								<uni-list-item title="班级排名" :rightText="exam.class_rank" />
								<uni-list-item title="年级排名" :rightText="exam.school_rank" />
							</uni-list>
						</uni-card>
					</uni-collapse-item>
				</uni-collapse>
			</uni-card>
		</view>
	</view>
</template>

<script>
	import {
		reactive,
		onMounted,
		watch,
		toRefs
	} from 'vue';
	import {
		onShow,
		onLoad
	} from '@dcloudio/uni-app';
	import vkDataGoodsSkuPopup from '@/components/vk-data-goods-sku-popup/vk-data-goods-sku-popup.vue';
	import useStudentStore from '@/store/studentStore.js';
	import {
		defaultGradeColumn
	} from '@/utils/enum';

	export default {
		components: {
			vkDataGoodsSkuPopup,
		},
		setup() {
			///在方法内调用，否则真机运行有问题
			const studentStore = useStudentStore();
			studentStore.setStudents(studentStore.students);
			const placeholderStyle = "color:#000000;font-size:14px;font-weight:546;";
			const gradeList = defaultGradeColumn;

			// 响应式数据，新增用于控制折叠项展开状态的数组
			const state = reactive({
				userInfo: {},
				gradeGoodsInfo: {},
				gradeTermPopupData: {
					show: false,
					goods_id: "001",
					theme: "default",
					showClose: true,
					maskCloseAble: true,
				},
				activeCollapseItems: [],
				selectedSubject: {}, // 修改为对象,使基于不同的exam
				totalScore: {}, // 修改为对象,使基于不同的exam
				averageScore: {}, // 修改为对象,使基于不同的exam
				totalFull: {}, // 修改为对象,使基于不同的exam
			});

			// 加载用户信息
			const loadUserInfoAsync = async (id) => {
				const student = studentStore.findStudent(id);
				console.log('loadUserInfoAsync student', student);
				if (student) {
					state.userInfo = student;
					// 外层循环开始，对每个examInfo对应的总分、平均分以及selectedSubject初始化
					state.userInfo.examInfo.forEach((examInfo, examInfoIndex) => {
						state.totalScore[examInfoIndex] = {};
						state.averageScore[examInfoIndex] = {};
						state.selectedSubject[examInfoIndex] = {};
						state.totalFull[examInfoIndex] = {};
						examInfo.examList.forEach((exam, examIndex) => {
							state.selectedSubject[examInfoIndex][examIndex] = [];
							state.totalScore[examInfoIndex][examIndex] = 0; // 初始化每个考试的总分，设为0
							state.averageScore[examInfoIndex][examIndex] = 0; // 初始化每个考试的平均分，设为0
							state.totalFull[examInfoIndex][examIndex] = 0; // 初始化每个考试的满分和，设为0
						});
					});
					return state.userInfo;
				} else {
					console.error(`未找到id为${id}的学生信息`);
				}
			};

			// 打开年级学期选择弹窗
			const openGradeTermPopup = () => {
				state.gradeGoodsInfo = getGradeTermGoodsInfo(state.gradeTermPopupData.goods_id);
				if (!state.gradeGoodsInfo) {
					console.error('未获取到有效的年级学期商品信息');
					return;
				}
				state.gradeTermPopupData.show = true;
			};

			// 获取年级学期商品信息
			const getGradeTermGoodsInfo = (goodsId) => {
				console.log('goodsId', goodsId);
				return gradeList.find((item) => item._id === goodsId) || null;
			};

			// 年级学期选择弹窗打开时的监听方法
			const onOpenGradeTermPopup = () => {
				console.log("监听 - 打开年级学期选择组件");
				if (state.gradeTermPopupData.defaultSku && state.gradeTermPopupData.defaultSku.sku &&
					state.gradeTermPopupData.defaultSku.num) {
					state.$refs.gradeTermPopup.selectSku(state.gradeTermPopupData.defaultSku);
				}
			};

			// 年级学期选择弹窗关闭时的监听方法
			const onCloseGradeTermPopup = () => {
				console.log("监听 - 关闭年级学期选择组件");
			};

			// 年级学期选择确认后的逻辑处理
			const confirmGradeTermSelection = async (selectShop) => {
				console.log("监听 - 年级学期确认选择", selectShop);
				if (selectShop) {
					state.userInfo.stage = selectShop.sku_name_arr[0];
					state.userInfo.grade = selectShop.sku_name_arr[1];
					state.userInfo.term = selectShop.sku_name_arr[2];
				}
				// 主动调用，进行渲染刷新
				updateSubjectsByGrade(state.userInfo.grade, state.userInfo.term);
				setTimeout(() => {
					state.gradeTermPopupData.show = false;
				}, 300);
			};

			// 处理折叠项展开变化的方法
			const handleCollapseChange = (e, examInfoIndex) => {
				state.activeCollapseItems[examInfoIndex] = e;
			};

			const editExamInfo = (examInfoIndex, examIndex) => {
				uni.navigateTo({
					url: '/pages/score/score-info-edit?examInfoIndex=' + examInfoIndex + '&examIndex=' +
						examIndex
				});
			};

			const delExamInfo = (examInfoIndex, examIndex) => {
				console.log('e')
			};

			const selectSubject = (subject, examInfoIndex, examIndex) => {
				console.log('subject', subject)
				console.log('selectSubject state.selectedSubject', state.selectedSubject)
				console.log(' selectSubjectstate.selectedSubject2', state.selectedSubject[examInfoIndex][examIndex])
				const index = state.selectedSubject[examInfoIndex][examIndex].indexOf(subject);
				console.log(' selectSubjectstate. index', index)
				if (index === -1) {
					// 如果科目不在已选列表中，则添加
					subject.tagType = 'success';
					state.selectedSubject[examInfoIndex][examIndex].push(subject);
				} else {
					subject.tagType = 'default';
					// 如果科目已在已选列表中，则移除
					state.selectedSubject[examInfoIndex][examIndex].splice(index, 1);
				}
				// 根据最新的已选科目列表重新计算总分和平均分，传递外层和内层索引
				calculateTotalAndAverageScore(examInfoIndex, examIndex);
			};

			// 计算总分和平均分的方法
			const calculateTotalAndAverageScore = (examInfoIndex, examIndex) => {
				const selectedSubjects = state.selectedSubject[examInfoIndex][examIndex];
				console.log('selectedSubjects', selectedSubjects)
				let selectedNum = selectedSubjects.length;
				// 使用reduce方法计算总分，初始值设为0
				const totalScore = selectedSubjects.reduce((acc, subject) => acc + Number(subject.score), 0);
				const totalFull = selectedSubjects.reduce((acc, subject) => acc + Number(subject.full), 0);
				console.log('totalFull', totalFull)
				let averageScore = 0;
				if (selectedNum === 0) {
					averageScore = 0;
				} else {
					averageScore = totalScore / selectedNum;
				}
				// 使用toFixed方法保留一位小数，并更新响应式数据中的总分和平均分，使用双层索引
				state.totalScore[examInfoIndex][examIndex] = totalScore.toString();
				state.totalFull[examInfoIndex][examIndex] = totalFull.toString();
				state.averageScore[examInfoIndex][examIndex] = averageScore.toFixed(1).toString();
			};


			const handleCheckboxChange = (e) => {
				const checkedSubjects = [];
				e.detail.value.forEach((checkedValue) => {
					const subject = state.userInfo.examInfo[examInfoIndex].examList[examIndex].scoreList.find(
						s => s.score === checkedValue);
					if (subject) {
						checkedSubjects.push(subject);
					}
				});
				const totalScore = checkedSubjects.reduce((acc, subject) => acc + Number(subject.score), 0);
				const totalFull = checkedSubjects.reduce((acc, subject) => acc + Number(subject.full), 0);
				const selectedNum = checkedSubjects.length;
				let averageScore = 0;
				if (selectedNum === 0) {
					averageScore = 0;
				} else {
					averageScore = totalScore / selectedNum;
				}
				// 更新响应式数据中的总分和平均分
				state.totalScore[examInfoIndex][examIndex] = totalScore.toString();
				state.totalFull[examInfoIndex][examIndex] = totalFull.toString();
				state.averageScore[examInfoIndex][examIndex] = averageScore.toFixed(1).toString();
			};



			onLoad(async () => {
				await loadUserInfoAsync(1);
			});

			return {
				...toRefs(state),
				gradeList,
				placeholderStyle,
				openGradeTermPopup,
				onOpenGradeTermPopup,
				onCloseGradeTermPopup,
				confirmGradeTermSelection,
				handleCollapseChange,
				editExamInfo,
				delExamInfo,
				selectSubject,
				calculateTotalAndAverageScore,
			};
		}
	};
</script>

<style lang="scss" scoped>
	.tabContent {
		background: #fff;
		overflow: hidden;
	}

	.param-title {
		background: #f5f5f5;
		height: 80rpx;
		line-height: 80rpx;
		margin: 10rpx 30rpx 0;
		font-size: 28rpx;
		text-indent: 30rpx;
	}

	.param-item {
		height: 80rpx;
		line-height: 80rpx;
		font-size: 28rpx;
		border-bottom: 1rpx solid #f5f5f5;
		border-left: 1rpx solid #f5f5f5;
		border-right: 1rpx solid #f5f5f5;
		margin: 0 30rpx;
		padding: 0 30rpx;
		display: flex;
	}

	.param-item label {
		width: 260rpx;
		color: #999;
	}

	.title-box {
		display: flex;
		justify-content: flex-start;
		align-items: center;
		width: 92%; // 确保父容器宽度为100%
		margin-left: 30rpx;
		background: #f5f5f5;
		height: 60rpx;
	}

	.title-item {
		flex: 1; // 让每个exam-header平均分配空间
		white-space: nowrap; // 不换行显示
		color: red;
		position: sticky;
		font-size: 30rpx;
		font-weight: 550;
		width: 30%;
		margin: 0rpx 30rpx;

	}

	.collapse-title-box {
		display: flex;
		justify-content: space-evenly; // 使用space - evenly来更均匀地分布元素
		align-items: center;
		width: 100%; // 确保父容器宽度为100%
	}

	.collapse-title {
		flex: 1; // 让每个exam-header平均分配空间
		text-align: center; // 文本居中显示
		white-space: nowrap; // 不换行显示
		overflow: hidden;
		text-overflow: ellipsis; // 超出部分显示省略号
		font-size: 30rpx;
		color: green;

	}

	.term-font {
		font-size: 25rpx; // 根据需要调整字体大小
	}

	// 调整考试信息表格相关样式，针对新的折叠结构下的内容展示
	.exam-info {
		display: flex;
		justify-content: space-around; // 均匀分布子元素
		align-items: center;
		// margin-top: 10rpx;
	}

	.mini-button-box {
		display: flex;
		justify-content: space-between;
		align-items: center;
		width: 92%;
	}

	.mini-button-box button {
		margin: 0 30rpx 0 60rpx; ///上右下左
		height: 50rpx;
		text-wrap: nowrap;
	}

	.button {
		width: 85%;
		font-size: 28rpx;
		font-weight: 550;
		border-style: hidden;
		margin-right: 80rpx;
	}

	.text {
		font-size: 28rpx;
		font-weight: 550;
	}

	.subject-text-box {
		display: flex;
		flex-direction: column;
	}

	.text-name {
		margin-top: 10rpx;
		font-size: 50rpx;
		text-align: center;
	}

	.text-score {
		margin-top: 10rpx;
		text-align: center;
		color: hotpink;
		font-size: 28rpx;
	}

	.checkbox-group {
		display: flex;
		flex-wrap: wrap;
	}

	.checkbox {
		display: flex;
		flex-direction: row;
	}

	.subject-name {
		font-size: 28rpx;
		font-weight: 600;
		color: rgb(164, 175, 3);
		margin-top: -5rpx;
		padding-right: 30rpx;
	}

	.subject-score {
		font-size: 10rpx;
		color: red;
		margin-top: -10rpx;
		padding-right: 30rpx;
	}
</style>